package com.core.utils;

import java.util.Date;

public class QueryBuilder {
	
    private StringBuilder builder = new StringBuilder();

    private void build(String name, Object value, String comparison) {
        if (value instanceof String) {
            builder.append(String.format("%s %s '%s'", name, comparison, value));
        } else if (value instanceof Date) {
            builder.append(String.format("%s %s '%3$tY-%3$tm-%3$td'", name, comparison, value));
        } else {
            builder.append(String.format("%s %s %s", name, comparison, value));
        }
    }

    public QueryBuilder and(String name, Object value) {
        return and(name, value, "=");
    }

    public QueryBuilder and(String name, Object value, String comparison) {
        if (builder.length() > 0) {
            builder.append(" AND ");
        }

        build(name, value, comparison);

        return this;
    }

    public QueryBuilder or(String name, Object value) {
        return or(name, value, "=");
    }

    public QueryBuilder or(String name, Object value, String comparison) {
        if (builder.length() > 0) {
            builder.append(" OR ");
        }

        build(name, value, comparison);

        return this;
    }

    public QueryBuilder and(QueryBuilder query) {
        if (builder.length() > 0) {
            builder.append(" AND ");
        }

        builder.append(String.format("(%s)", query.toString()));

        return this;
    }

    public QueryBuilder or(QueryBuilder query) {
        if (builder.length() > 0) {
            builder.append(" OR ");
        }

        builder.append(String.format("(%s)", query.toString()));

        return this;
    }

    @Override
    public String toString() {
        return builder.toString();
    }
}
